package com.inno.sms.aspect;

import cn.hutool.core.util.StrUtil;

import com.inno.sms.error.SmsException;
import com.inno.sms.properties.FeignProperties;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 内部接口切面
 * @author shenzeyang
 */
@Component
@Aspect
@Slf4j
public class HiddenAspect {
    private final FeignProperties feignProperties;
    public HiddenAspect(FeignProperties feignProperties){
        this.feignProperties = feignProperties;
    }
    @Pointcut("@annotation(com.inno.sms.annotiation.Hidden)")
    public void pointcut() {
    }
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String requestHeader = request.getHeader(feignProperties.getName());
        if (!(StringUtils.isNotBlank(requestHeader) && StrUtil.equals(requestHeader, feignProperties.getValue()))){
            throw  SmsException.of("您无权访问该接口");
        }
        return point.proceed();
    }
}
